package com.sczc.esm27.collection.devices.response;

import cn.hutool.core.util.ByteUtil;
import com.alibaba.fastjson.JSONObject;
import com.sczc.esm27.collection.core.message.IMessageHandle;
import com.sczc.esm27.collection.core.util.ContextUtils;
import com.sczc.esm27.collection.entity.DataMessage;
import com.sczc.esm27.collection.entity.ESM27ResponseMessageEntity;
import com.sczc.esm27.collection.entity.SensorData;
import com.sczc.esm27.collection.mq.TopicSender;
import com.sczc.esm27.collection.netty.DataDecoder;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class SensorDataHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
    private static final Logger logger = LogManager.getLogger(SensorDataHandle.class);
    private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

    @Override
    public boolean isHandle(ESM27ResponseMessageEntity esm27ResponseMessageEntity) {
        return esm27ResponseMessageEntity.getCommandCode() == 0x01;
    }

    @Override
    public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity esm27ResponseMessageEntity) {
        if (esm27ResponseMessageEntity.getDatas() != null) {
            List<SensorData> sensorDataList = this.parseSensorData(esm27ResponseMessageEntity.getDatas());
            DataMessage message = new DataMessage(UUID.randomUUID().toString(), "sensor_data", sensorDataList, System.currentTimeMillis());
            logger.info("发送[传感器数据信息]到MQ完成:{}", JSONObject.toJSONString(message));
            topicSender.send(JSONObject.toJSONString(message));
        }
        return null;
    }

    private List<SensorData> parseSensorData(byte[] frameBody) {
        // 解析数据体
        List<SensorData> sensorDataList = new ArrayList<>();
        for (int i = 0; i < frameBody.length - 1; i += 10) {
            // 跳过前3个字节（预留）
            byte unitCode = frameBody[i + 3];  // 第4字节：单位代码
            byte sensorCode = frameBody[i + 4]; // 第5字节：传感器名称代码
            if (sensorCode == 0x00) {   // 预留
                continue;
            }
            // 判断是否为NFC数据
            Float sensorValue = null;
            String nfcData = null;
            if (sensorCode == 0x17) {
                // 这是NFC数据，提取并转换为ASCII码
                nfcData = extractNFCData(frameBody, i);
            } else {
                // 第6-9字节：传感器数值（IEEE 754单精度浮点数）
                byte[] sensorValueBytes = Arrays.copyOfRange(frameBody, i + 5, i + 9);
                sensorValue = ByteUtil.bytesToFloat(sensorValueBytes, ByteOrder.BIG_ENDIAN);
                // 保留2位小数
                sensorValue = (float) Math.round(sensorValue * 100) / 100;
            }
            // 第10字节：状态码
            byte statusCode = frameBody[i + 9];
            // 解析传感器名称和单位
            String sensorName = getSensorName(sensorCode);
            String unitName = getUnitName(unitCode);
            String displayName = getDisplayName(sensorCode);
            String status = getStatusName(statusCode);
            logger.info("传感器名称：{}  单位：{}  显示名称：{}  状态：{}  nfc数据:{}", sensorName, unitName, displayName, status, nfcData);
            SensorData sensorData = new SensorData(sensorName, displayName, unitName, status, sensorValue, nfcData);
            sensorDataList.add(sensorData);
        }
        return sensorDataList;
    }

    // NFC数据处理
    private String extractNFCData(byte[] frameBody, int offset) {
        // 提取NFC数据，假设NFC数据是4个字节
        byte[] nfcBytes = Arrays.copyOfRange(frameBody, offset + 5, offset + 9);
        logger.info("nfc数据：{}", com.sczc.esm27.collection.core.util.ByteUtil.bytesToHex(nfcBytes));
        return new String(nfcBytes, StandardCharsets.US_ASCII); // 转换为ASCII字符串
    }

    // 单位代码映射
    private String getUnitName(byte unitCode) {
        switch (unitCode) {
            case 0x00:
                return "--";
            case 0x01:
                return "%LEL";
            case 0x02:
                return "%VOL";
            case 0x03:
                return "PPM";
            case 0x04:
                return "mg/m³";
            case 0x05:
                return "mg/L";
            case 0x06:
                return "%";
            case 0x07:
                return "uSv";
            case 0x08:
                return "uSv/h";
            case 0x09:
                return "°C";
            case 0x0A:
                return "m/s";
            default:
                return "Unknown";
        }
    }

    private String getDisplayName(byte nameCode) {
        switch (nameCode) {
            case 0x00:
                return "--";             // 预留
            case 0x01:
                return "一氧化碳";         // CO
            case 0x02:
                return "氢气";             // H2
            case 0x03:
                return "硫化氢";           // H2S
            case 0x04:
                return "氨气";             // NH3
            case 0x05:
                return "二氧化硫";         // SO2
            case 0x06:
                return "氢氟酸";           // HF
            case 0x07:
                return "氯化氢";           // HCL
            case 0x08:
                return "氰化氢";           // HCN
            case 0x09:
                return "二氧化氮";         // NO2
            case 0x0A:
                return "氯气";             // CL2
            case 0x0B:
                return "挥发性有机化合物"; // VOC
            case 0x0C:
                return "氧气";             // O2
            case 0x0D:
                return "可燃气体";         // EX
            case 0x0E:
                return "甲烷";             // CH4
            case 0x0F:
                return "一氧化氮";         // NO
            case 0x10:
                return "臭氧";             // O3
            case 0x11:
                return "二氧化碳";         // CO2
            case 0x12:
                return "γ射线辐射";        // GAMMA
            case 0x13:
                return "可吸入颗粒物";     // PM2.5
            case 0x14:
                return "有毒气体";         // TOX
            case 0x15:
                return "纬度";             // Latitude
            case 0x16:
                return "经度";             // Longitude
            case 0x17:
                return "NFC数据";           // NFC
            case 0x18:
                return "加速度传感器";     // AG
            default:
                return "未知传感器";          // Unknown
        }
    }

    // 传感器名称映射
    private String getSensorName(byte nameCode) {
        switch (nameCode) {
            case 0x00:
                return "--";             // 预留
            case 0x01:
                return "CO";
            case 0x02:
                return "H2";
            case 0x03:
                return "H2S";
            case 0x04:
                return "NH3";
            case 0x05:
                return "SO2";
            case 0x06:
                return "HF";
            case 0x07:
                return "HCL";
            case 0x08:
                return "HCN";
            case 0x09:
                return "NO2";
            case 0x0A:
                return "CL2";
            case 0x0B:
                return "VOC";
            case 0x0C:
                return "O2";
            case 0x0D:
                return "EX";
            case 0x0E:
                return "CH4";
            case 0x0F:
                return "NO";
            case 0x10:
                return "O3";
            case 0x11:
                return "CO2";
            case 0x12:
                return "GAMMA";
            case 0x13:
                return "PM2.5";
            case 0x14:
                return "TOX";
            case 0x15:
                return "Latitude";
            case 0x16:
                return "Longitude";
            case 0x17:
                return "NFC";
            case 0x18:
                return "AG";
            default:
                return "Unknown";
        }
    }


    // 状态码映射
    private String getStatusName(byte statusCode) {
        switch (statusCode) {
            case 0x00:
                return "无状态";
            case 0x01:
                return "正常";
            case 0x02:
                return "1级报警";
            case 0x03:
                return "2级报警";
            case 0x04:
                return "3级报警";
            case 0x05:
                return "超量程";
            case 0x06:
                return "加速度传感器警报";
            case 0x0F:
                return "传感器未开启";
            default:
                return "Unknown";
        }
    }

    public static void main(String[] args) {
        // 4 字节数组 {01, 00, 00, 00}
        byte[] byteArray = {0x66, 0x67, 0x68, 0x69};  // 十六进制表示

        // 将字节数组转换为 ASCII 字符串
        String asciiString = new String(byteArray, StandardCharsets.US_ASCII);

        // 输出结果
        System.out.println("ASCII String: " + asciiString);
    }
}
